import cn from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';

import Item from './Item';
import s from './style.module.css';

function Breadcrumb({ className, prefix, children }) {
	const childArr = [].concat(children).filter(Boolean);
	const childLen = childArr.length;
	const prefixArr = [prefix];

	return (
		<div className={cn(className, s.breadcrumb)}>
			{childArr.reduce((arr, item, idx) => {
				if (!item) return null;

				prefixArr.push(item.key);
				const isLast = idx === childLen - 1;

				if (isLast) {
					arr.push(
						React.cloneElement(item, {
							...item.props,
							active: isLast,
							href: prefixArr.join('/'),
						})
					);
				} else {
					arr.push(
						React.cloneElement(item, {
							...item.props,
							href: prefixArr.join('/'),
						}),
						<div key={`${item.key}-slash`} className={s.slash}>
							{'/'}
						</div>
					);
				}

				return arr;
			}, [])}
		</div>
	);
}

Breadcrumb.propTypes = {
	className: PropTypes.string,
	prefix: PropTypes.string,
	children: PropTypes.node,
};
Breadcrumb.defaultProps = {
	className: '',
	prefix: '',
};
Breadcrumb.Item = Item;

export default Breadcrumb;
export { Item };
